<template>
    <div>
        <basic-container>
            <div class="app-container">
                <el-form :model="otherQuery" ref="queryForm" size="small" :inline="true">

                    <el-form-item label="机种名称">
                        <el-select style="width: 180px;" v-model="otherQuery.aircraft_id" placeholder="请选择" clearable>
                            <el-option v-for="item in roleOptions" :key="item.aircraft_id" :label="item.aircraft"
                                :value="item.aircraft_id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="设备名称">
                        <el-select style="width: 180px;" v-model="otherQuery.facility_id" placeholder="请选择" clearable>
                            <el-option v-for="item in menuList" :key="item.facility_id" :label="item.name"
                                :value="item.facility_id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini"
                            @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>

                </el-form>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini"
                            @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-download" size="mini"
                            @click="handleExport">导出</el-button>
                    </el-col>

                </el-row>
                <template>
                    <el-table :data="tableData" v-loading="loading" element-loading-text="拼命加载中"
                        element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
                        ref="table" style="width: 100%" border>
                        
                        <el-table-column prop="aircraft_name" label="机种名称" align="center" >
                        </el-table-column>
                        
                        <el-table-column prop="facility_name" label="设备名称" align="center" >
                        </el-table-column>
                        
                        <el-table-column prop="op_user" label="创建/修改用户" align="center" >
                        </el-table-column>
                        
                        <el-table-column prop="pdf_name" label="文件名" align="center" >
                            <template slot-scope="scope">
                                <el-link type="primary" @click="viewPDF(scope.row)" :underline="false">
                                    {{ scope.row.pdf_name }}
                                </el-link>
                            </template>
                        </el-table-column>
                        
                        <el-table-column prop="remark" label="SOP备注标签" align="center" >
                        </el-table-column>
                        
                        <el-table-column prop="time" label="创建/修改时间" align="center" >
                        </el-table-column>

                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
                            <template slot-scope="scope">
                                <el-button size="mini" type="text" icon="el-icon-edit"
                                    @click="handleUpdate(scope.row)">编辑</el-button>
                                <el-button size="mini" type="text" icon="el-icon-view"
                                    @click="viewPDF(scope.row)">查看PDF</el-button>
                                <el-button size="mini" type="text" icon="el-icon-delete" style="color: #f56c6c;"
                                    @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </template>

            </div>
            <pagination v-show="toNum > 0" :total="toNum" :page.sync="otherQuery.index" :limit.sync="otherQuery.size"
                @pagination="gitMeassList" />
        </basic-container>

        <!-- PDF查看对话框 -->
        <el-dialog title="PDF查看" :visible.sync="pdfDialogVisible" width="90%" top="5vh">
            <div style="height: 70vh; overflow: auto;">
                <iframe v-if="currentPdfSrc" :src="currentPdfSrc" style="width: 100%; height: 100%; border: none;"></iframe>
                <div v-else style="text-align: center; padding: 50px;">
                    <el-empty description="PDF文件加载失败"></el-empty>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="pdfDialogVisible = false">关闭</el-button>
            </span>
        </el-dialog>

        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="机种名称" prop="aircraft_id" v-if="isAdd">
                    <el-select v-model="form.aircraft_id" placeholder="请选择机种" style="width: 100%">
                        <el-option v-for="item in roleOptions" :key="item.aircraft_id" :label="item.aircraft"
                            :value="item.aircraft_id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="机种名称" prop="aircraft_name" v-else>
                    <el-input v-model="form.aircraft_name" placeholder="请输入机种名称" disabled />
                </el-form-item>
                
                <el-form-item label="设备名称" prop="facility_id" v-if="isAdd">
                    <el-select v-model="form.facility_id" placeholder="请选择设备" style="width: 100%">
                        <el-option v-for="item in menuList" :key="item.facility_id" :label="item.name"
                            :value="item.facility_id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="设备名称" prop="facility_name" v-else>
                    <el-input v-model="form.facility_name" placeholder="请输入设备名称" disabled />
                </el-form-item>
                
                <el-form-item label="当前文件名" prop="pdf_name" v-if="!isAdd">
                    <el-input v-model="form.pdf_name" placeholder="当前文件名" disabled />
                </el-form-item>
                
                <el-form-item :label="isAdd ? 'PDF文件' : '更换PDF文件'" prop="pdfFile" v-if="isAdd">
                    <el-upload
                        ref="upload"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :before-upload="beforeUpload"
                        :on-change="handleFileChange"
                        :on-success="handleUploadSuccess"
                        :on-error="handleUploadError"
                        :file-list="fileList"
                        :auto-upload="false"
                        accept=".pdf"
                        action="">
                        <el-button slot="trigger" size="small" type="primary" icon="el-icon-folder-opened">选择PDF文件</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传PDF文件，且文件大小不超过50MB</div>
                    </el-upload>
                    <!-- 隐藏的input用于表单验证 -->
                    <el-input v-model="form.pdfFile" style="display: none;"></el-input>
                </el-form-item>
                
                <el-form-item :label="isAdd ? 'PDF文件' : '更换PDF文件(可选)'" prop="pdfFileEdit" v-if="!isAdd">
                    <el-upload
                        ref="uploadEdit"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :before-upload="beforeUpload"
                        :on-change="handleFileChange"
                        :on-success="handleUploadSuccess"
                        :on-error="handleUploadError"
                        :file-list="fileList"
                        :auto-upload="false"
                        accept=".pdf"
                        action="">
                        <el-button slot="trigger" size="small" type="primary" icon="el-icon-folder-opened">选择新PDF文件</el-button>
                        <div slot="tip" class="el-upload__tip">不选择文件则只修改备注标签，选择文件则同时更换PDF文件</div>
                    </el-upload>
                    <!-- 隐藏的input用于表单验证 -->
                    <el-input v-model="form.pdfFileEdit" style="display: none;"></el-input>
                </el-form-item>
                
                <el-form-item label="SOP备注标签" prop="remark">
                    <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入SOP备注标签" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button 
                    type="primary" 
                    @click="submitForm"
                    :loading="submitLoading"
                    :disabled="submitLoading">
                    {{ submitLoading ? '提交中...' : '确 定' }}
                </el-button>
                <el-button @click="cancel" :disabled="submitLoading">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    getkindList,
    gitsop,
    delsop,
    addsop,
    eitsop,
    getdkind,
    getdTaskkind
} from "@/api/arftsop";

export default {
    data() {
        return {
            tableTile: ['机种名称', '产品编码'],
            checked: false,
            roleOptions: [],
            tabPosition: "left",
            tableData: [],
            loading: false,
            showSearch: true,
            value1: [],
            total: 1,
            inMess: [],
            menuList: [],
            // 弹出层标题
            title: "",
            open: false,
            isAdd: false, // 是否为新增操作
            toNum: 0,
            isExpandAll: false,
            restaurants: [],
            activeName: null,
            refreshTable: true,
            otherQuery: {
                facility_id: null,
                aircraft_id: null,
                index: 1,
                size: 10,
            },
            queryParams: {
                index: 1,
                size: 1000,
            },
            form: {},
            rules: {
                aircraft_id: [
                    { required: true, message: "请选择机种", trigger: "change" }
                ],
                facility_id: [
                    { required: true, message: "请选择设备", trigger: "change" }
                ],
                remark: [
                    { required: true, message: "SOP备注标签不能为空", trigger: "blur" }
                ],
                pdfFile: [
                    { 
                        validator: (rule, value, callback) => {
                            console.log('PDF文件验证:', {
                                isAdd: this.isAdd,
                                selectedFile: this.selectedFile,
                                formPdfFile: this.form.pdfFile
                            });
                            
                            if (this.isAdd && !this.selectedFile) {
                                callback(new Error('请选择PDF文件'));
                            } else {
                                callback();
                            }
                        }, 
                        trigger: ["change", "blur"]
                    }
                ]
            },
            // PDF查看相关
            pdfDialogVisible: false,
            currentPdfSrc: null,
            // 文件上传相关
            fileList: [],
            selectedFile: null,
            pdfFile: null, // 用于表单验证的字段
            submitLoading: false, // 提交按钮loading状态
        };
    },
    created() {

    },

    mounted() {
        this.getList()
        this.getdkindList();
        this.gitMeassList();
    },
 
    methods: {
        getList() {
            getkindList(this.queryParams).then((response) => {
                this.menuList = response.data.data;
                console.log(this.menuList, "设备列表");
            });
        },
        cancel() {
            this.open = false;
            this.isAdd = false;
            this.submitLoading = false; // 重置提交loading状态
            this.reset();
        },
        handleUpdate(row) {
            this.open = true;
            this.isAdd = false;
            this.title = "编辑SOP";
            this.form = JSON.parse(JSON.stringify(row));
        },
        
        // 新增SOP记录
        handleAdd() {
            this.open = true;
            this.isAdd = true;
            this.title = "新增SOP";
            this.reset();
            
            // 延迟清除表单验证状态，确保表单已经渲染
            this.$nextTick(() => {
                setTimeout(() => {
                    if (this.$refs.form) {
                        this.$refs.form.clearValidate();
                        console.log('已清除表单验证状态');
                    }
                }, 100);
            });
        },
        
        // 文件数量超限处理
        handleExceed(files, fileList) {
            console.log(files, fileList);
            
            this.$message.warning('最多只能上传1个PDF文件');
        },
        
        // 文件选择变化处理
        handleFileChange(file, fileList) {
            console.log('=== handleFileChange 被调用 ===');
            console.log('file:', file);
            console.log('fileList:', fileList);
            console.log('当前模式 isAdd:', this.isAdd);
            
            if (file && file.raw) {
                const rawFile = file.raw;
                console.log('原始文件:', rawFile);
                
                // 检查文件类型
                const fileName = rawFile.name.toLowerCase();
                const isPDFByName = fileName.endsWith('.pdf');
                const isPDFByType = rawFile.type === 'application/pdf';
                const isLt50M = rawFile.size / 1024 / 1024 < 50;
                
                console.log('文件验证:', { isPDFByName, isPDFByType, isLt50M });
                
                if (!isPDFByName && !isPDFByType) {
                    this.$message.error('只能上传PDF文件!');
                    return;
                }
                if (!isLt50M) {
                    this.$message.error('上传文件大小不能超过 50MB!');
                    return;
                }
                
                // 设置文件状态
                this.selectedFile = rawFile;
                this.fileList = fileList;
                this.pdfFile = rawFile;
                
                if (this.isAdd) {
                    this.form.pdfFile = rawFile.name;
                } else {
                    this.form.pdfFileEdit = rawFile.name;
                }
                
                console.log('=== 文件状态已设置 ===');
                console.log('selectedFile:', this.selectedFile);
                console.log('form.pdfFile:', this.form.pdfFile);
                
                // 触发表单验证
                this.$nextTick(() => {
                    if (this.$refs.form) {
                        if (this.isAdd) {
                            this.$refs.form.validateField('pdfFile');
                        } else {
                            this.$refs.form.validateField('pdfFileEdit');
                        }
                        console.log('表单验证已触发');
                    }
                });
            }
        },
        
        // 上传前验证
        beforeUpload(file) {
            console.log('=== beforeUpload 被调用，阻止自动上传 ===');
            console.log('文件名:', file.name);
            return false; // 阻止自动上传
        },
        
        // 上传成功处理（这里不会被调用，因为阻止了自动上传）
        handleUploadSuccess(response, file, fileList) {
            console.log(response, file, fileList);
            
            // 这个方法在手动上传时不会被调用
        },
        
        // 上传失败处理
        handleUploadError(err, file, fileList) {

            this.$message.error('文件上传失败');
            console.log(err, file, fileList);
            
        },
        
        // 删除SOP记录
        handleDelete(row) {
            this.$confirm(`确定要删除文件 "${row.pdf_name}" 吗？`, '删除确认', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const deleteData = {
                    sop_id: parseInt(row.sop_id) // 确保sop_id是数字类型
                };
                
                console.log('删除请求数据:', deleteData);
                console.log('row.sop_id类型:', typeof row.sop_id, '值:', row.sop_id);
                
                delsop(deleteData).then(res => {
                    console.log('删除成功响应:', res);
                    this.$message.success("删除成功");
                    // 刷新表格数据
                    this.gitMeassList();
                }).catch(error => {
                    console.error('删除错误详情:', error);
                    console.error('错误响应:', error.response);
                    console.error('请求配置:', error.config);
                    
                    // 处理不同的错误状态码
                    if (error.response && error.response.data) {
                        const { status, msg } = error.response.data;
                        switch (status) {
                            case 4000:
                                this.$message.error("文件类型错误，只能是PDF类型");
                                break;
                            case 4001:
                                this.$message.error("未找到此机种，操作失败");
                                break;
                            case 4002:
                                this.$message.error("未找到此设备，操作失败");
                                break;
                            case 4003:
                                this.$message.error("已上传此工站机种SOP, 只能更新操作");
                                break;
                            default:
                                this.$message.error(msg || "删除失败");
                        }
                    } else {
                        this.$message.error("删除失败");
                    }
                });
            }).catch(() => {
                // 用户取消删除
            });
        },
        
        // 查看PDF文件
        viewPDF(row) {
            if (row.pdf_base64) {
                // 将base64转换为blob URL
                try {
                    const byteCharacters = atob(row.pdf_base64);
                    const byteNumbers = new Array(byteCharacters.length);
                    for (let i = 0; i < byteCharacters.length; i++) {
                        byteNumbers[i] = byteCharacters.charCodeAt(i);
                    }
                    const byteArray = new Uint8Array(byteNumbers);
                    const blob = new Blob([byteArray], { type: 'application/pdf' });
                    this.currentPdfSrc = URL.createObjectURL(blob);
                    this.pdfDialogVisible = true;
                } catch (error) {
                    this.$message.error('PDF文件解析失败');
                    console.error('PDF解析错误:', error);
                }
            } else {
                this.$message.warning('该记录没有PDF文件');
            }
        },

        handleExport() {
            this.$confirm('是否将数据导出为Excel文档？').then(() => {
                const params = new URLSearchParams();
                this.otherQuery.aircraft_id == null ? '' : params.append('aircraft_id', this.otherQuery.aircraft_id);
                this.otherQuery.facility_id == null ? '' : params.append('facility_id', this.otherQuery.facility_id);
                const url = new URL('http://192.168.20.252:8080/api/query/sop/output');
                url.search = params.toString();
                window.location.href = url.toString();
            })
        },
        
        gitMeassList() {
            this.loading = true;
            this.tableData = []
            gitsop(this.otherQuery).then((res) => {
                this.tableData = res.data.data;
                console.log(this.tableData, 'SOP数据');
                this.toNum = res.data.total;
                this.loading = false;
            }).catch(error => {
                this.loading = false;
                this.$message.error('获取数据失败');
                console.error('获取数据错误:', error);
            });
        },
        
        handleQuery() {
            this.otherQuery.index = 1; // 重置到第一页
            this.gitMeassList();
        },
        
        resetQuery() {
            this.otherQuery = {
                facility_id: null,
                aircraft_id: null,
                index: 1,
                size: 10,
            };
            this.gitMeassList();
        },

        getdkindList() {
            getdkind().then((res) => {
                this.roleOptions = res.data.data;
                console.log(this.roleOptions, '机种列表');
            });
        },
        
        querySearchAsync(queryString) {
            if (queryString == null) return;

            let quey = {
                name: queryString,
            };
            getdTaskkind(quey).then((res) => {
                this.restaurants = res.data.data;
            });
        },
        
        submitForm() {
            console.log('开始提交表单:', {
                isAdd: this.isAdd,
                selectedFile: this.selectedFile,
                form: this.form
            });
            
            // 设置提交loading状态
            this.submitLoading = true;
            
            this.$refs["form"].validate(valid => {
                console.log('表单验证结果:', valid);
                
                if (!valid) {
                    // 表单验证失败，清除loading状态
                    this.submitLoading = false;
                    return;
                }
                
                if (this.isAdd) {
                    // 新增操作
                    if (!this.selectedFile) {
                        this.$message.error("请选择PDF文件");
                        this.submitLoading = false; // 清除loading状态
                        return;
                    }
                    
                    console.log('准备提交新增请求');
                    const formData = new FormData();
                    formData.append('remark', this.form.remark);
                    formData.append('aircraft_id', this.form.aircraft_id);
                    formData.append('facility_id', this.form.facility_id);
                    formData.append('data', this.selectedFile);
                    
                    addsop(formData).then(res => {
                        console.log(res);
                        this.$message.success("新增成功");
                        this.open = false;
                        this.submitLoading = false; // 清除loading状态
                        // 刷新表格数据
                        this.gitMeassList();
                    }).catch(error => {
                        this.submitLoading = false; // 清除loading状态
                        console.error('新增错误:', error);
                        
                        // 处理不同的错误状态码
                        if (error.response && error.response.data) {
                            const { status, msg } = error.response.data;
                            switch (status) {
                                case 4000:
                                    this.$message.error("文件类型错误，只能是PDF类型");
                                    break;
                                case 4001:
                                    this.$message.error("未找到此机种，操作失败");
                                    break;
                                case 4002:
                                    this.$message.error("未找到此设备，操作失败");
                                    break;
                                case 4003:
                                    this.$message.error("已上传此工站机种SOP, 只能更新操作");
                                    break;
                                default:
                                    this.$message.error(msg || "新增失败");
                            }
                        } else {
                            this.$message.error("新增失败");
                        }
                    });
                } else {
                    // 编辑操作 - 使用eitsop接口
                    const formData = new FormData();
                    formData.append('sop_id', this.form.sop_id);
                    formData.append('remark', this.form.remark);
                    
                    // 如果选择了新文件，则添加到FormData中
                    if (this.selectedFile) {
                        formData.append('data', this.selectedFile);
                    }
                    
                    eitsop(formData).then(res => {
                        console.log(res);
                        this.$message.success("修改成功");
                        this.open = false;
                        this.submitLoading = false; // 清除loading状态
                        // 刷新表格数据
                        this.gitMeassList();
                    }).catch(error => {
                        this.submitLoading = false; // 清除loading状态
                        console.error('修改错误:', error);
                        
                        // 处理不同的错误状态码
                        if (error.response && error.response.data) {
                            const { status, msg } = error.response.data;
                            switch (status) {
                                case 4000:
                                    this.$message.error("文件类型错误，只能是PDF类型");
                                    break;
                                case 4001:
                                    this.$message.error("未找到此机种，操作失败");
                                    break;
                                default:
                                    this.$message.error(msg || "修改失败");
                            }
                        } else {
                            this.$message.error("修改失败");
                        }
                    });
                }
            });
        },
        
        reset() {
            this.form = {
                aircraft_id: null,
                aircraft_name: '',
                facility_id: null,
                facility_name: '',
                op_user: '',
                pdf_base64: '',
                pdf_name: '',
                remark: '',
                sop_id: null,
                time: '',
                pdfFile: null, // 重置PDF文件验证字段
                pdfFileEdit: null // 重置编辑模式PDF文件验证字段
            };
            // 清理文件上传状态
            this.fileList = [];
            this.selectedFile = null;
            this.pdfFile = null; // 重置用于表单验证的字段
            this.submitLoading = false; // 重置提交loading状态
            
            if (this.$refs.upload) {
                this.$refs.upload.clearFiles();
            }
            if (this.$refs.uploadEdit) {
                this.$refs.uploadEdit.clearFiles();
            }
            if (this.$refs["form"]) {
                this.$refs["form"].resetFields();
            }
        },
    },
    
    // 组件销毁时清理blob URL
    beforeDestroy() {
        if (this.currentPdfSrc) {
            URL.revokeObjectURL(this.currentPdfSrc);
        }
    }
};
</script>

<style lang="scss" scoped>
.message {
    width: 198%;
    background: #f8f8f9;
    display: flex;
    overflow-x: scroll;
}

.activeClass {
    color: red;
}

::v-deep .el-table .el-table__body-wrapper::-webkit-scrollbar {
    height: 15px !important;
    /* 设置水平滚动条的高度 */
}

.dialog-footer {
    text-align: right;
}

// 移除不需要的样式
.expand-button {
    color: #409EFF;
    cursor: pointer;
    font-size: 13px;
    margin-top: 5px;

    &:hover {
        text-decoration: underline;
    }
}

.dynamic-form-row {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 10px;
    border-bottom: 1px dashed #eee;
    padding-bottom: 10px;

    &:last-child {
        border-bottom: none;
    }
}

.dynamic-form-item {
    flex: 1;
    min-width: 200px;
    margin-right: 10px;
    margin-bottom: 0;

    :deep(.el-form-item__label) {
        width: 100px !important;
    }

    :deep(.el-form-item__content) {
        margin-left: 100px !important;
    }
}
</style>